package com.ccit.employee.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ccit.common.baiduFace.constant.FaceConstant;
import com.ccit.common.baiduFace.pojo.FaceUserDTO;
import com.ccit.common.baiduFace.pojo.ImageU;
import com.ccit.common.baiduFace.result.FaceResult;
import com.ccit.common.baiduFace.service.FaceManage;
import com.ccit.common.baiduFace.util.PicStringToImgU;
import com.ccit.common.client.UserClient;
import com.ccit.common.exception.GymException;
import com.ccit.common.result.Result;
import com.ccit.common.utils.RedisUtils;
import com.ccit.employee.service.AttendanceService;
import com.ccit.employee.service.CourseBillService;
import com.ccit.employee.service.EmployeeService;
import com.ccit.employee.service.MemberService;
import com.ccit.model.Attendance;
import com.ccit.model.CourseOrder;
import com.ccit.model.Employee;
import com.ccit.model.dto.CoachDto;
import com.ccit.model.vo.admin.AdminUpdateVo;
import com.ccit.model.vo.employee.EmployeeVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.List;


@RestController
@Api(tags = "职工管理")
@RequestMapping("/employee")
public class EmployeeController {
    @Autowired
    private EmployeeService employeeService;
    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private AttendanceService attendanceService;
    @Autowired
    private RedisUtils redisUtils;
    @Autowired
    private UserClient userClient;
    @Autowired
    private CourseBillService courseBillService;
    @Autowired
    private MemberService memberService;

    /*
     * 人脸注册
     * */
    @ApiOperation("人脸注册")
    @PostMapping("/faceRegister")
    public Result faceRegister(@RequestParam MultipartFile file, @RequestPart String employee) throws Exception {
        /**
         * 人脸检测
         */
        JSONObject object = JSON.parseObject(employee);
        ImageU imageU = PicStringToImgU.translate(file);
        FaceResult result = FaceManage.faceDetect(imageU);
        String data = result.getData().getString(FaceConstant.FACE_LIST);
        System.out.println(data);
        //人脸注册
        FaceUserDTO<String> userDTO = new FaceUserDTO<>();
        userDTO.setGroupId("employee");
        userDTO.setUserId(Long.toString(object.getInteger("id")));
        userDTO.setUser(object.getString("name") + object.getString("phone"));
        FaceManage.faceRegister(userDTO, imageU);
        return Result.ok("注册成功");
    }

    @ApiOperation("获取所有员工信息")
    @GetMapping("/getAll")
    public Result getAllEmployee() {
        List<Employee> list;
        String key = "allEmployee";
        boolean has = redisUtils.hasKey(key);
        if (has) {
            list = (List<Employee>) redisUtils.get(key);
        } else {
            list = employeeService.list();
            redisUtils.set(key, list);
        }
        return Result.ok(list);
    }

    @ApiOperation("分页获取员工信息")
    @GetMapping("/getByPage/{current}/{size}")
    public Result getEmployeeByPage(@PathVariable Integer current,
                                    @PathVariable Integer size) {
        String key = "employeePage" + current + size;
        boolean has = redisUtils.hasKey(key);
        Page<Employee> page;
        if (has) {
            //如果存在该对象
            page = (Page<Employee>) redisUtils.get(key);
        } else {
            //mysql拿数据
            Page<Employee> employeePage = new Page(current, size);
            page = employeeService.page(employeePage);
            //存入redis
            redisUtils.set(key, page);
        }
        return Result.ok(page);
    }

    @GetMapping("/getCoachByPage/{current}/{size}")
    public Result<Page> getCoachByPage(@PathVariable Integer current,
                                       @PathVariable Integer size) {

//        List<Employee> list= employeeService.getCoachByPage();
        List<Employee> list = employeeService.getCoachByPage();
        List<CoachDto> coachDtos = new ArrayList<>();
        list.forEach(employee -> {
            CoachDto coachDto = new CoachDto();
            coachDto.setName(employee.getName());
            coachDto.setId(employee.getId());
            coachDto.setType(employee.getType());
            coachDto.setPhone(employee.getPhone());
            coachDto.setDeleted(employee.getDeleted());
            double courseMoney = courseBillService.getMonthMoneyByName(coachDto.getName());
            double memberMoney = memberService.getMonthMoneyByCoach(coachDto.getName());
            coachDto.setCourseMoney(courseMoney);
            coachDto.setMemberMoney(memberMoney);
            coachDto.setJx(courseMoney + memberMoney);
            coachDtos.add(coachDto);
        });

        //对list分页
        Page<CoachDto> page = new Page<>(current, size);
        page.setRecords(coachDtos);
        page.setTotal(list.size());
        page.setCurrent(current);
        return Result.ok(page);
    }

    @ApiOperation("根据id获取员工信息")
    @GetMapping("/getByPage/{id}")
    public Employee getEmployeeById(@PathVariable Long id) {
        Employee employee = employeeService.getById(id);
        if (employee == null) {
            throw new GymException(202, "没有此员工");
        }
        return employee;
    }

    @ApiOperation("根据idList获取员工信息")
    @GetMapping("/getByPage")
    public List<Employee> getEmployeeByIds(@RequestParam List<Long> idList) {
        idList.forEach(id -> {
            Employee employee = getEmployeeById(id);
            if (employee == null) {
                throw new GymException(202, "没有此员工");
            }
        });

        List<Employee> employees = employeeService.listByIds(idList);
        return employees;
    }

    @ApiOperation("获取所有教练")
    @GetMapping("/getAllCoach")
    public Result getAllCoach() {
        String key = "coachList";
        boolean has = redisUtils.hasKey(key);
        if (has) {
            List<Employee> coachList = (List<Employee>) redisUtils.get("coachList");
            return Result.ok(coachList);
        } else {
            QueryWrapper<Employee> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("type", "教练");
            List<Employee> list = employeeService.list(queryWrapper);
            if (list.size() > 0) {
                redisUtils.set("coachList", list);
                return Result.ok(list);
            } else {
                throw new GymException(204, "数据异常");
            }
        }
    }

    @ApiOperation("获取所有检修员")
    @GetMapping("/getAllMaintainer")
    public Result getAllMaintainer() {
        String key = "maintainerList";
        boolean has = redisUtils.hasKey(key);
        List<Employee> list;
        if (has) {
            list = (List<Employee>) redisUtils.get("maintainerList");
        } else {
            QueryWrapper<Employee> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("type", "检修员");
            list = employeeService.list(queryWrapper);
            if (list.size() > 0) {
                redisUtils.set("maintainerList", list);
            } else {
                throw new GymException(204, "数据异常");
            }
        }
        return Result.ok(list);
    }

    @ApiOperation("添加新的员工信息")
    @PostMapping("/saveEmployee")
    public Result saveEmployee(@RequestBody Employee employee) {
        if (employee.getType() == "教练") {
            redisUtils.del("coachList");
        }
        //姓名查重
        QueryWrapper<Employee> wrapper = new QueryWrapper();
        wrapper.eq("name", employee.getName());
        wrapper.select("name");
        List<Employee> employees = employeeService.list(wrapper);
        if (employees.size() > 0) {
            //当已存在时
            throw new GymException(202, "添加失败,用户名被占用!");
        } else {
            boolean flag = employeeService.save(employee);
            Attendance attendance = new Attendance();
            attendance.setEmployeeId(employee.getId());
            attendance.setName(employee.getName());
            attendance.setType(employee.getType());
            attendance.setPhone(employee.getPhone());
            attendanceService.save(attendance);
            if (flag == true) {
                //批量模糊删除所有包含keys的数据
                redisUtils.deleteRedisKeys("employeePage");
                redisUtils.deleteRedisKeys("allEmployee");
                redisUtils.deleteRedisKeys("coachList");
                redisUtils.deleteRedisKeys("maintainerList");
                redisUtils.deleteRedisKeys("allAttendance");
                redisUtils.deleteRedisKeys("attendancePage");
                redisUtils.deleteRedisKeys("attendanceToDayPage");
                redisUtils.deleteRedisKeys("AttendanceYear");
                return Result.ok();
            } else {
                return Result.fail("添加失败");
            }
        }
    }

    @ApiOperation("修改员工信息")
    @PutMapping("/updateInfo")
    public Result updateEmployeeInfo(@RequestBody EmployeeVo employeeVo) {
        QueryWrapper<Employee> queryWrapper = new QueryWrapper();
        queryWrapper.eq("phone", employeeVo.getPhone());
        List<Employee> employeeList = employeeService.list(queryWrapper);
        if (employeeList.size() > 0) {
            Employee upEmployee = employeeList.get(0);
            upEmployee.setPhone(employeeVo.getNewPhone());
            upEmployee.setName(employeeVo.getName());
            boolean flag = employeeService.updateById(upEmployee);
            if (flag) {
                //批量模糊删除所有包含keys的数据
                redisUtils.deleteRedisKeys("allAttendance");
                redisUtils.deleteRedisKeys("attendancePage");
                redisUtils.deleteRedisKeys("attendanceToDayPage");
                redisUtils.deleteRedisKeys("AttendanceYear");
                redisUtils.deleteRedisKeys("employeePage");
                redisUtils.deleteRedisKeys("allEmployee");
                redisUtils.deleteRedisKeys("coachList");
                redisUtils.deleteRedisKeys("maintainerList");
                return Result.ok("修改成功");
            } else
                throw new GymException(501, "修改失败");
        } else {
            throw new GymException(502, "查无此员工");
        }
    }

    @ApiOperation("修改员工==>修改管理员")
    @PutMapping("/updateEmployee")
    public Result updateEmployeeToAdmin(@RequestBody Employee employee) {
        //查找当前员工信息
        QueryWrapper<Employee> queryWrapper = new QueryWrapper<>();
        System.out.println(employee.getId());
        queryWrapper.eq("id", employee.getId());
        Employee upEmployee = employeeService.getOne(queryWrapper);
        //封装管理员信息
        AdminUpdateVo adminUpdateVo = new AdminUpdateVo();
        adminUpdateVo.setNewPhone(employee.getPhone());
        adminUpdateVo.setPhone(upEmployee.getPhone());
        adminUpdateVo.setNewName(employee.getName());
        adminUpdateVo.setPhone(upEmployee.getName());

        upEmployee.setName(employee.getName());
        upEmployee.setPhone(employee.getPhone());
        boolean result = true;
        System.out.println(employee.getType());
        if (employee.getType().equals("前台")) {
            //    修改管理员信息
            System.out.println(result);
            result = userClient.updateAdminInfoByEmployee(adminUpdateVo);
            System.out.println(result);
        }
        boolean flag = employeeService.updateById(upEmployee);
        if (flag && result) {
            //批量模糊删除所有包含keys的数据
            redisUtils.deleteRedisKeys("allAttendance");
            redisUtils.deleteRedisKeys("attendancePage");
            redisUtils.deleteRedisKeys("attendanceToDayPage");
            redisUtils.deleteRedisKeys("AttendanceYear");
            redisUtils.deleteRedisKeys("employeePage");
            redisUtils.deleteRedisKeys("allEmployee");
            redisUtils.deleteRedisKeys("coachList");
            redisUtils.deleteRedisKeys("maintainerList");
            return Result.ok("修改成功");
        } else
            throw new GymException(501, "修改失败");
    }


    /* @ApiOperation("解雇删除员工信息")
     @DeleteMapping("/dismiss/{id}")
     public Result removeEmployee(@PathVariable("id") Integer id) {
         //批量模糊删除所有包含keys的数据
         redisUtils.deleteRedisKeys("employee");
         redisUtils.del("coachList");
         System.out.println(id);
         Employee employee = employeeService.getById(id);
         System.out.println(employee);
         String name = employee.getName();
         if (employee.getType().equals("前台")) {
             //身份为前台 ,先删除管理员信息
             Boolean flag = employeeService.removeAdminByName(name);
             if (!flag) {
                 throw new GymException(203, "服务异常");
             }
             //当管理员信息删除成功
         }
         boolean ff = employeeService.removeById(id);
         if (ff) {
             //批量模糊删除所有包含keys的数据
             redisUtils.deleteRedisKeys("employeePage");
             redisUtils.deleteRedisKeys("allEmployee");
             redisUtils.deleteRedisKeys("coachList");
             redisUtils.deleteRedisKeys("maintainerList");
             return Result.ok();
         } else {
             return Result.fail("删除失败");
         }
     }
 */
    @Transactional
    @ApiOperation("解雇删除员工信息")
    @DeleteMapping("/dismiss/{phone}")
    public Result removeEmployee(@PathVariable("phone") String phone) {
        //批量模糊删除所有包含keys的数据
        redisUtils.deleteRedisKeys("employee");
        redisUtils.del("coachList");
        QueryWrapper<Employee> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("phone", phone);
        Employee employee = employeeService.getOne(queryWrapper);
        System.out.println(employee);
        String name = employee.getName();
        if (employee.getType().equals("前台")) {
            //身份为前台 ,先删除管理员信息
            Boolean flag = employeeService.removeAdminByName(name);
//            if (!flag) {
//                throw new GymException(203, "服务异常");
//            }
            //当管理员信息删除成功
        }
        boolean ff = employeeService.removeById(employee.getId());
        if (ff) {
            //批量模糊删除所有包含keys的数据
            redisUtils.deleteRedisKeys("allAttendance");
            redisUtils.deleteRedisKeys("attendancePage");
            redisUtils.deleteRedisKeys("attendanceToDayPage");
            redisUtils.deleteRedisKeys("AttendanceYear");
            redisUtils.deleteRedisKeys("employeePage");
            redisUtils.deleteRedisKeys("allEmployee");
            redisUtils.deleteRedisKeys("coachList");
            redisUtils.deleteRedisKeys("maintainerList");
            return Result.ok();
        } else {
            return Result.fail("删除失败");
        }
    }
}
